module Ch03(safeSecond, tidySecond, myLength, mean, palindrome,
            isPalindrome, sortByLength, intersperse, Tree(..), height) where

-- See also Plane.hs.

import Data.List (sortBy)
import Data.Function

safeSecond [] = Nothing
safeSecond xs = if null (tail xs)
                then Nothing
                else Just (head (tail xs))

tidySecond (_:x:_) = Just x
tidySecond _ = Nothing

myLength :: [a] -> Int
myLength [] = 0
myLength (_:xs) = 1 + myLength xs

mean xs = (sum xs) / (fromIntegral (length xs))

palindrome xs = xs ++ reverse xs

isPalindrome xs = xs == reverse xs

sortByLength = sortBy (compare `on` length)

intersperse _ [] = []
intersperse _ [x] = x
intersperse sep (x:xs) = x ++ (sep : intersperse sep xs)

data Tree a = Node a (Tree a) (Tree a)
            | Empty
              deriving (Show)

height Empty = 0
height (Node _ l r) = 1 + (max (height l) (height r))
